package com.unionftech.content_login.ui.login

import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.core.widget.addTextChangedListener
import com.unionftech.common.R.*
import com.unionftech.common.base.BaseFragment
import com.unionftech.common.common.language.DynamicResourceManager
import com.unionftech.common.utils.RegexUtils
import com.unionftech.content_login.R
import com.unionftech.content_login.ui.forget.UFForgetPasswordActivity
import com.unionftech.common.utils.CheckInputUtil

class EmailLoginFragment : BaseFragment() {
    private val mEtEmail: EditText by lazy { mRootView.findViewById(R.id.et_email) }
    private val mTvEmailError: TextView by lazy { mRootView.findViewById(R.id.tv_email_error) }
    private val mIvClearEmail: ImageView by lazy { mRootView.findViewById(R.id.iv_clear_email) }
    private lateinit var mCommonFragment: LoginCommonFragment
    private var mLoginListener: ((account: String, password: String) -> Unit)? = null
    private var mInitEmail: String? = null


    companion object {
        private const val PARAMS_INIT_EMAIL = "PARAMS_INIT_EMAIL"

        @JvmStatic
        fun newInstance(initEmail: String?) = EmailLoginFragment().apply {
            arguments = Bundle().apply {
                putString(PARAMS_INIT_EMAIL, initEmail)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            mInitEmail = it.getString(PARAMS_INIT_EMAIL)
        }
    }

    override fun inflaterContentView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_email_login, container, false)
    }

    override fun initData() {
        super.initData()
        mCommonFragment = LoginCommonFragment.newInstance()
    }

    override fun initLanguageText() {
        super.initLanguageText()
        mEtEmail.hint = DynamicResourceManager.getString(mContext, string.email)
    }

    private fun requestLogin() {
        val email = mEtEmail.text.toString()
        val pwd = mCommonFragment.getLoginPassword()
        mLoginListener?.invoke(email, pwd)
    }

    private fun checkInput(): Boolean {
        return CheckInputUtil.checkInput(
            mEtEmail.text.toString(),
            RegexUtils.EMAIL_REGEX,
            mEtEmail,
            mTvEmailError,
            string.email_empty,
            string.email_format_incorrect
        )
    }

    override fun setListener() {
        super.setListener()
        mCommonFragment.setCompleteListener { result ->
            mEtEmail.clearFocus()
            if (checkInput() && result) {
                requestLogin()
            }
        }
        mCommonFragment.setPasswordChangeCallback { enable ->
            val result = enable && !TextUtils.isEmpty(mEtEmail.text)
            mCommonFragment.setLoginEnable(result)
        }
        mCommonFragment.setGotoForgetCallback {
            UFForgetPasswordActivity.startThis(mActivity, 0)
        }
        mIvClearEmail.setOnClickListener(this)
        mEtEmail.setOnFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                //去除错误边框展示
                mEtEmail.isSelected = false
                setEmailClear(mEtEmail.text)
            } else {
                mIvClearEmail.visibility = View.GONE
                checkInput()
            }
        }
        mEtEmail.addTextChangedListener { text ->
            val result =
                !TextUtils.isEmpty(text) && !TextUtils.isEmpty(mCommonFragment.getLoginPassword())
            mCommonFragment.setLoginEnable(result)
            setEmailClear(text)
        }
    }

    private fun setEmailClear(text: Editable?) {
        if (!TextUtils.isEmpty(text)) {
            mIvClearEmail.visibility = View.VISIBLE
        } else {
            mIvClearEmail.visibility = View.GONE
        }
    }

    override fun setView() {
        super.setView()
        hideTitleBar()
        //editText的左右padding不一致，目前只能在代码中设置，在xml中设置不支持rtl
        val dp16 = mContext.resources.getDimension(dimen.dp_16).toInt()
        val dp48 = mContext.resources.getDimension(dimen.dp_48).toInt()
        mEtEmail.setPaddingRelative(dp16, 0, dp48, 0)
        mRootView.setBackgroundColor(mContext.getColor(android.R.color.transparent))
        val transaction = childFragmentManager.beginTransaction()
        transaction.add(R.id.fl_login_common, mCommonFragment)
        transaction.commitNowAllowingStateLoss()
        childFragmentManager.executePendingTransactions()
        if (!TextUtils.isEmpty(mInitEmail)) {
            mEtEmail.setText(mInitEmail)
        }
    }

    fun resetPasswordData() {
        if (::mCommonFragment.isInitialized) {
            mCommonFragment.resetPasswordData()
        }
    }

    fun setLoginListener(listener: (account: String, password: String) -> Unit) {
        this.mLoginListener = listener
    }

    fun setInitEmail(email: String?) {
        mInitEmail = email
        mEtEmail.setText(mInitEmail)
        mEtEmail.clearFocus()
        mEtEmail.isSelected = false
        mTvEmailError.visibility = View.INVISIBLE
    }


    override fun doClick(v: View?) {
        super.doClick(v)
        when (v?.id) {
            R.id.iv_clear_email -> {
                mEtEmail.setText("")
            }
        }
    }
}